$(function () {

    var id = $("#searchMerchantId").val();
    var page =  $("#searchMerchantPage").val();
    if (page==3){
        $("#bill").css({'font-size':'15px','font-weight':'bold'});
        $("#turnover").css({'font-size':'13px','font-weight':'normal'});
        queryBill();
    }
$('.name:first').css({'font-size':'15px','font-weight':'bold'});
$('.name').click(function () {
    $(this).css({'font-size':'15px','font-weight':'bold'});
    $(this).siblings().css({'font-size':'13px','font-weight':'normal'});
});
queryTurnover();
//账户流水
$('#turnover').click(function () {
    queryTurnover();
});
function queryTurnover() {

        // $('#turnover').css({'font-size':'15px','font-weight':'bold'});
        $('.turnover').css('display', 'block');
        $('.details').css('display', 'none');
        $('.bill').css('display', 'none');
        $('.Printing').css('display', 'none');
        $('.see').css('display', 'none');

        $('.query ').on('click', function () {
            var type = $('#test3').val();
            // active[type] ? active[type].call(this) : '';
        });

        layui.use('laydate', function () {
            var laydate = layui.laydate;
            laydate.render({
                elem: '#demoReload'
                , type: 'month'
            });
        });
        layui.use('table', function (obj) {
            var table = layui.table;

            //方法级渲染
            table.render({
                elem: '#LAY_table_user'
                , url: "/query/getSettlementById?id=" + id
                , cols: [[
                    {field: 'id', title: "id", width: 100}
                    , {field: 'num', title: '序号', width: 200, sort: true}
                    , {field: 'time', title: '时间', width: 350, sort: true}
                    , {field: 'type', title: '操作', width: 350}
                    , {field: 'money', title: '操作金额(元)', width: 350, sort: true}
                    , {field: 'after', title: '余额', width: 350}

                ]]
                , id: 'testReload'
                , page: true
                , height: 472
                , response: {
                    statusCode: 666
                }
                // ,even:true //每行条纹
                , limits: [10, 15, 20, 25, 30]
                , limit: 10 //每页默认显示的数量
                , initSort: {field: 'time', type: 'asc'}
                // ,toolbar:'#toolbarDemo'  //导出打印
                , parseData: function (res) {
                    console.log(res.data)
                    $(".rechargemoney").text(res.data.rechargemoney);
                    $(".settlementmoney").text(res.data.settlementmoney);
                    return {
                        "code": res.code,
                        "msg": res.msg,
                        "count": res.data.count,
                        "data": res.data.flowLineList
                    };

                }
                , done: function (res, curr, count) {
                    $("[data-field='id']").css('display', 'none');
                    $("#name").text(res.name);
                    $("#month").text(res.month);
                    $("[data-field='type']").children().each(function () {
                        if ($(this).text() == '1') {
                            $(this).text("结算")
                        } else if ($(this).text() == '0') {
                            $(this).text("充值");
                        }
                    });

                    $("[data-field='time']").children().each(function () {
                        var re = /^[0-9]+.?[0-9]*/;//判断字符串是否为数字//判断正整数/[1−9]+[0−9]∗]∗/
                        if (re.test($(this).text())) {
                            $(this).text(formatDate($(this).text()));
                        }
                    });
                }

            });

            table.on('sort(Receipt)', function (obj) {
                table.reload('testReload', {
                    initSort: obj
                });
            });
            table.reload('testReload', {});
            var $ = layui.$, active = {
                reload: function () {
                    var demoReload = $('#demoReload');
                    //执行重载
                    table.reload('testReload', {
                        page: {
                            curr: 1 //重新从第 1 页开始
                        }
                        , where: {
                            month: demoReload.val()
                        }
                    });
                }
            };
            $('.query').on('click', function () {
                var type = $(this).data('type');
                active[type] ? active[type].call(this) : '';
            });

            //监听行单击事件（单击事件为：rowDouble）
            //其中的user对应的是 table中的lay-filter="user"
            table.on('row(Receipt)', function (obj) {
                var data = obj.data;
                console.log(data);
                var id = data['id'];
                var type = data['type'];
                var time = formatDate(data['time']);
                var after = data['after'];
                var money = data['money'];
                var chasingmoney = "";
                if (after < 0) {
                    chasingmoney = after
                }
                var before = after - money;
                $.ajax({
                    type: 'POST',
                    url: '/query/getReceiptMsg',
                    async: false,
                    data: {"id": id, "type": type},
                    dataType: 'json',
                    success: function (result) {
                        if (result.code == 666) {
                            if (type == 1) {
                                layui.use(['layer', 'form'], function () {
                                    var layer = layui.layer;
                                    layer.open({
                                        type: 1,
                                        title: ['回执单', 'font-size:25px;font-weight:lighter;background-color:white;height:50px;margin-top:10px'],
                                        // skin: 'layui-layer-rim', //加上边框
                                        area: ['1000px', '400px'], //宽高
                                        content: "<div class='dialog-hui'>" +
                                            "<div class='dialog-title'><p class='dialog-p'>回执类型：结算</p></div>" +
                                            "     <div class=\"panel-group\" id=\"steps\">\n" +
                                            "         <!--Step 1 -->\n" +
                                            "        <div class=\"panel panel-default\">\n" +
                                            "            <div class=\"panel-heading\">\n" +
                                            "                <h4 class=\"panel-title\"><a data-toggle=\"collapse\" class=\"type\" data-parent=\"#steps\" href=\"#stepOne\"></a></h4>\n" +
                                            "            </div>\n" +
                                            "            <div id=\"stepTwo\" class=\"panel-collapse  in\">\n" +
                                            "                <div class=\"panel-body data-box\">\n" +
                                            "                  \n" +
                                            "\n" +
                                            "                    <table id=\"print-content2\" border=\"1\" width=\"100%\"  cellpadding=\"0\" cellspacing=\"0\" style='border-collapse:collapse;table-layout:fixed;'>\n" +
                                            "                        <tr height=\"45\" style=\"text-align: center;font-size:14px\">\n" +
                                            "                            <td colspan=\"2\" class=\"on\">账户名称</td>\n" +
                                            "                            <td colspan=\"10\" id=\"comname\">" + result.data.settlement.merchantname + "</td>\n" +
                                            "                        </tr>\n" +
                                            "                        <tr height=\"45\" style=\"text-align: center;font-size:14px\">\n" +
                                            "                            <td colspan=\"2\" class=\"on\">联系人</td>\n" +
                                            "                            <td colspan=\"2\" id=\"linkman\">" + result.data.settlement.phone + "</td>\n" +
                                            "                            <td colspan=\"2\" class=\"on\">结算时间</td>\n" +
                                            "                            <td colspan=\"2\" id=\"time\">" + time + "</td>\n" +
                                            "                            <td colspan=\"2\" class=\"on\">结算人</td>\n" +
                                            "                            <td colspan=\"2\" id=\"settlePerson\">" + result.data.settlement.companyName + "</td>\n" +
                                            "                        </tr>\n" +
                                            "                        <tr height=\"45\" style=\"text-align: center;font-size:14px\">\n" +
                                            "                            <td colspan=\"2\" class=\"on\">追问欠款(元)</td>\n" +
                                            "                            <td colspan=\"2\" id=\"mon\">" + chasingmoney + "</td>\n" +
                                            "                            <td colspan=\"2\" class=\"on\">结算前余额(元)</td>\n" +
                                            "                            <td colspan=\"2\" id=\"beforesettle\">" + result.data.settlement.beforesettle + "</td>\n" +
                                            "                            <td colspan=\"2\" class=\"on\">结算后余额(元)</td>\n" +
                                            "                            <td colspan=\"2\" id=\"aftersettle\">" + after + "</td>\n" +
                                            "                        </tr>\n" +
                                            "                    </table>\n" +
                                            "                    <div id=\"column\">\n" +
                                            "                    </div>\n" +
                                            "                    <div class=\"alarm\"></div>\n" +
                                            "                </div>\n" +
                                            "            </div>\n" +
                                            "        </div>\n" +
                                            "\n" +
                                            "    </div>\n" +
                                            "<div class=\"modal-footer\" style='margin-top: 28px;'>\n" +
                                            "    <a class=\"btn green\" id=\"print-click2\" onclick='exportTable2();'>导出Excel</a>\n" +
                                            "    <a class=\"btn blue\"  id=\"printout2\" onclick=\"printout2()\">打印</a>\n" +
                                            "   <a class=\"btn red\"  id=\"\" onclick=\"closebox()\">取消</a>\n" +
                                            "   \n" +
                                            "</div>" +
                                            "</div><hr class='layui-bg-gray'></div>"
                                    });
                                    //标注选中样式
                                    obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
                                })
                            } else if (type == 0) {
                                var channel = "";
                                if (result.data.recharge.channel == 1) {
                                    channel = "现金"
                                } else if (result.data.recharge.channel == 1) {
                                    channel = "微信"
                                } else {
                                    channel = "支付宝"
                                }
                                layui.use(['layer', 'form'], function () {
                                    var layer = layui.layer;
                                    layer.open({
                                        type: 1,
                                        title: ['回执单', 'font-size:25px;font-weight:lighter;background-color:white;height:50px;margin-top:10px'],
                                        // skin: 'layui-layer-rim', //加上边框
                                        area: ['1000px', '400px'], //宽高
                                        content: "<div class='dialog-hui'>" +
                                            "<div class='dialog-title'><p class='dialog-p'>回执类型：充值</p></div>" +
                                            "   <div class=\"panel-group\" id=\"steps\">\n" +
                                            "         <!--Step 1 -->\n" +
                                            "        <div class=\"panel panel-default\">\n" +
                                            "            <div class=\"panel-heading\">\n" +
                                            "                <h4 class=\"panel-title\"><a data-toggle=\"collapse\" class=\"type\" data-parent=\"#steps\" href=\"#stepOne\"></a></h4>\n" +
                                            "            </div>\n" +
                                            "            <div id=\"stepOne\" class=\"panel-collapse  in\">\n" +
                                            "                <div class=\"panel-body data-box2\">\n" +
                                            "                    <table id=\"print-content\" border=\"1\" width=\"100%\"  cellpadding=\"0\" cellspacing=\"0\" style='border-collapse:collapse;table-layout:fixed;'>\n" +
                                            "                        <tr height=\"45\" style=\"text-align: center;font-size:14px\">\n" +
                                            "                            <td colspan=\"2\" class=\"on\">账户名称</td>\n" +
                                            "                            <td colspan=\"10\" class=\"name2\" style=\"border:inherit \">" + result.data.recharge.merchantname + "</td>\n" +
                                            "                        </tr>\n" +
                                            "                        <tr height=\"45\" style=\"text-align: center;font-size:14px\">\n" +
                                            "                            <td colspan=\"2\" class=\"on\">联系人</td>\n" +
                                            "                            <td colspan=\"2\" class=\"phone1\">" + result.data.recharge.phone + "</td>\n" +
                                            "                            <td colspan=\"2\" class=\"on\">充值时间</td>\n" +
                                            "                            <td colspan=\"2\" class=\"recordtime\">" + time + "</td>\n" +
                                            "                            <td colspan=\"2\" class=\"on\">收费人</td>\n" +
                                            "                            <td colspan=\"2\" class=\"settlePerson\">" + result.data.recharge.companyName + "</td>\n" +
                                            "                        </tr>\n" +
                                            "                        <tr height=\"45\" style=\"text-align: center;font-size:14px\">\n" +
                                            "                            <td colspan=\"2\" class=\"on\">付款途径</td>\n" +
                                            "                            <td colspan=\"2\" class=\"channel\">" + channel + "</td>\n" +
                                            "                            <td colspan=\"2\" class=\"on\">充值金额(元)</td>\n" +
                                            "                            <td colspan=\"2\" class=\"rechargeamount\">" + result.data.recharge.rechargeamount + "</td>\n" +
                                            "                            <td colspan=\"2\" class=\"on\">分项账户</td>\n" +
                                            "                            <td colspan=\"2\" class=\"wallet\">预付费子账户钱包</td>\n" +
                                            "                        </tr>\n" +
                                            "                        <tr height=\"45\" style=\"text-align: center;font-size:14px\">\n" +
                                            "                            <td colspan=\"2\" class=\"on\">充值前余额(元)</td>\n" +
                                            "                            <td colspan=\"2\" class=\"beforerecharge\">" + result.data.recharge.beforerecharge + "</td>\n" +
                                            "                            <td colspan=\"2\" class=\"on\">充值后余额(元)</td>\n" +
                                            "                            <td colspan=\"6\" class=\"afterrecharge\">" + result.data.recharge.afterrecharge + "</td>\n" +
                                            "                        </tr>\n" +
                                            "                    </table>\n" +
                                            "                    <div id=\"column\">\n" +
                                            "                    </div>\n" +
                                            "                    <div class=\"alarm\"></div>\n" +
                                            "                </div>\n" +
                                            "            </div>\n" +
                                            "        </div>\n" +
                                            "\n" +
                                            "    </div>\n" +
                                            "<div class=\"modal-footer\">\n" +
                                            "    <a class=\"btn btn-primary\"  id=\"print-click\" onclick='exportTable1();'>导出excel</a>\n" +
                                            "    <a class=\"btn blue\"  id=\"printout\" onclick=\"printout()\">打印</a>\n" +
                                            "    <a class=\"btn red\"  id=\"\" onclick=\"closebox()\">取消</a>\n" +
                                            "</div>" +
                                            "</div><hr class='layui-bg-gray'></div>"
                                    });
                                    //标注选中样式
                                    obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
                                })
                            }
                        } else {
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        if (XMLHttpRequest.status == 555) {
                            var layer;
                            layui.use(['layer', 'form'], function () {
                                layer = layui.layer
                                layer.alert('未登录,请登录后操作', {icon: 7}, function (index) {
                                    //do something
                                    layer.close(index);
                                    top.location.href = "/login";
                                });
                            });
                        } else {
                            var layer;
                            layui.use(['layer', 'form'], function () {
                                layer = layui.layer
                                layer.alert('页面加载失败', {icon: 7}, function (index) {
                                    //do something
                                    layer.close(index);
                                });
                            });
                        }
                    },
                });
            });
        });
    }
$('#bill').click(function () {
    queryBill();
    // $('.layui-table-cell').css({"height":"36px","line-height":"36px"});
});
function queryBill() {
    $('.bill').css('display','block');
    $('.details').css('display','none');
    $('.turnover').css('display','none');
    $('.Printing').css('display','block');
    $('.see').css('display','none');

    layui.use('laydate', function() {
        var  laydate = layui.laydate;
        laydate.render({
            elem: '#demoReload2'
            ,type:'year'
        });

    });
    layui.use('table', function(){
        var table = layui.table;

        //方法级渲染
        table.render({
            elem: '#LAY_table_user2'
            ,url: "/query/settlementBill?id="+id
            ,cols: [[
                {field:'month', title: '月份', width: 100,sort: true}
                ,{field:'beforetime', title: '账单起始时间', width:150}
                ,{field:'nowtime', title: '账单结算时间', width: 150}
                ,{field:'eleccost', title: '电子账户费用', width:130}
                ,{field:'watercost', title: '水子账户费用', width:130}
                ,{field:'gascost', title: '气子账户费用', width:130}
                ,{field:'shareeleccost', title: '电子分摊费用', width:130}
                ,{field:'sharewatercost', title: '水子分摊费用', width:130}
                ,{field:'sharegascost', title: '气子账户费用', width:130}
                ,{field:'cost', title: '合计', width:150}
                ,{fixed: 'right', title:'操作', toolbar: '#barDemo', width:200}
            ]]
            ,id: 'testReload'
            ,page: true
            ,height: 500
            ,response: {
                statusCode: 666
            }
            // ,even:true //每行条纹
            ,limits: [12]
            ,limit: 12 //每页默认显示的数量
            ,initSort: {field:'time', type:'asc'}//默认时间排序
            ,toolbar:'#toolbarDemo'  //导出打印
            ,parseData:function (res) {
                $(".balance").text(res.data.balance);
                $(".cost").text(res.data.costCount);
                return{
                    "code":res.code,
                    "msg":res.msg,
                    "count":res.data.settlementList.length,
                    "data":res.data.settlementList,
                };
            }
            , done: function(res, curr, count){
                // $(".layui-table-box").find("[data-field='id']").css("display","none");
                $("[data-field='nowtime']").children().each(function(){
                    if($(this).text()=='0'){
                        $(this).text("")
                    }
                });
                $("[data-field='beforetime']").children().each(function(){
                    if($(this).text()=='0'){
                        $(this).text("")
                    }
                });
                $("[data-field='beforetime']").children().each(function(){
                    var re = /^[0-9]+.?[0-9]*/;//判断字符串是否为数字//判断正整数/[1−9]+[0−9]∗]∗/
                    if (re.test($(this).text())) {
                        $(this).text(formatDate($(this).text()));
                    }
                });
                $("[data-field='nowtime']").children().each(function(){
                    var re = /^[0-9]+.?[0-9]*/;//判断字符串是否为数字//判断正整数/[1−9]+[0−9]∗]∗/
                    if (re.test($(this).text())) {
                        $(this).text(formatDate($(this).text()));
                    }
                });
            }
        });
        var $ = layui.$, active = {
            reload: function(){
                var demoReload = $('#demoReload2');
                //执行重载
                table.reload('testReload', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    ,where: {
                        year: demoReload.val()
                    }
                });
            }
        };
        $('#query').on('click', function(){
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });
        //监听行单击事件（单击事件为：rowDouble）
        //其中的user对应的是 table中的lay-filter="user"
        table.on('row(user)', function(obj){
            var data = obj.data;
            var id=data['id'];
            $('#seeid').val(id);
            //标注选中样式
            obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
        });
        var merchantid= $('#merchantid').val();

        table.on('tool(user)', function(obj){
            var data = obj.data;
            if(obj.event === 'day'){
                window.location.href="/query/queryDayPage?mon="+data.month+'&id='+id;
            }else if(obj.event === 'edit'){
                window.location.href="/query/queryBillPage?mon="+data.month+'&id='+id;
            }
        });
    });
}
});
function printout() {
    debugger;
    var newWindow;
    //打开一个新的窗口
    newWindow = window.open();
    // 是新窗口获得焦点
    newWindow.focus();
    //保存写入内容
    var newContent = "<extend name=\"Company:Public:base\" />";
    newContent += document.getElementById("LAY_table_user2").outerHTML;
    newContent += "</body></html>"
    // 将HTML代码写入新窗口中
    newWindow.document.write(newContent);
    newWindow.print();
    // close layout stream
    newWindow.document.close();
    //关闭打开的临时窗口
    newWindow.close();
    return false;
};
function formatDate(timestamp) {
    if (timestamp) {
        var time = new Date(timestamp*1000);
        var y = time.getFullYear();
        var M = time.getMonth() + 1;
        var d = time.getDate();
        var h = time.getHours();
        var m = time.getMinutes();
        var s = time.getSeconds();
        return y + '-' + addZero(M) + '-' + addZero(d) + ' ' + addZero(h) + ':' + addZero(m) + ':' + addZero(s);
    } else {
        return '';
    }
}
function addZero(m) {
    return m < 10 ? '0' + m : m;
}
//根据key,返回url中指定参数的value
function getParameter(url,paramKey)
{
    var paramValue = "";
    url = url.substr(url.indexOf("?")+1);
    var paramArray = new String(url).split("&");
    $.each(paramArray,function(i, paramStr){
        var params = paramStr.split("=");
        if(paramKey == params[0])
        {
            paramValue =  decodeURI(params[1]);
            return false;
        }
    });
    return paramValue;
}
function  gettype(str) {
    if (str==0){
        return "电";
    }else if (str==1) {
        return "水";
    }else{
        return "气";
    }
}
function closebox() {
    var layer;
    layui.use(['layer', 'form'],function() {
        layer = layui.layer;
        layer.close(layer.index);
    });
}
//表格导出
function exportTable1() {
    // 获取头部和body
    var data = LAY_EXCEL.tableToJson(document.getElementById('print-content')) // 或者 $('#LAY-EXPORT-TEST')
    // console.log(data)
    var exportData = []
    exportData.push.apply(exportData, data.head)
    exportData.push.apply(exportData, data.body)
    // console.log(exportData)
    LAY_EXCEL.exportExcel(exportData, '充值详细.xlsx', 'xlsx')
}
//表格导出
function exportTable2() {
    // 获取头部和body
    var data = LAY_EXCEL.tableToJson(document.getElementById('print-content2')) // 或者 $('#LAY-EXPORT-TEST')
    // console.log(data)
    var exportData = []
    exportData.push.apply(exportData, data.head)
    exportData.push.apply(exportData, data.body)
    // console.log(exportData)
    LAY_EXCEL.exportExcel(exportData, '结算详细.xlsx', 'xlsx')
}
function printout() {
    debugger;
    var newWindow;
    //打开一个新的窗口
    newWindow = window.open();
    // 是新窗口获得焦点
    newWindow.focus();
    //保存写入内容
    var newContent = "";
    newContent += document.getElementById("print-content").outerHTML;
    newContent += "</body></html>";
    // 将HTML代码写入新窗口中
    newWindow.document.write(newContent);
    newWindow.print();
    // close layout stream
    newWindow.document.close();
    //关闭打开的临时窗口
    newWindow.close();
    return false;
};

function printout2() {
    debugger;
    var newWindow;
    //打开一个新的窗口
    newWindow = window.open();
    // 是新窗口获得焦点
    newWindow.focus();
    //保存写入内容
    var newContent = "";
    newContent += document.getElementById("print-content2").outerHTML;
    newContent += "</body></html>";
    // 将HTML代码写入新窗口中
    newWindow.document.write(newContent);
    newWindow.print();
    // close layout stream
    newWindow.document.close();
    //关闭打开的临时窗口
    newWindow.close();
    return false;
};